import { Context, controller, inject, provide, post,config,get} from 'midway';
import {randomNum} from '../utils/randomNumber'
import {IFilesService,IUserService} from '../interface';
// import { IFilesService} from '../interface';
import * as fs from 'fs';
import * as path from 'path';
import * as awaitStream from 'await-stream-ready';
import * as sendToWormHole from 'stream-wormhole';
const moment = require('moment');
// import * as moment from 'moment';
// import {FileStream} from "egg";
// const fs = require('fs');
@provide()
@controller('/')
export class FilesController{

  @inject()
  ctx: Context;
  @inject()
  util
  @config()
  static;    
  @inject()
  logger; // 请求作用域，ContextLogger
  @inject('filesService')
  service: IFilesService;
  @inject('userService')
  user: IUserService;
  @post('/getFiles')
  async getFiles(){
    const stream = await this.ctx.getFileStream();
    console.log(stream)
    const filename = Date.now() + '' + randomNum(8) + stream.filename;
    await this.util.mkdirFolder('temporary')
    const target = path.join(`${this.static.dir}/temporary`, filename);
    const writeStream = fs.createWriteStream(target);
    try {
      // 写入文件
      await awaitStream.write(stream.pipe(writeStream));
    } catch (err) {
      // 关闭文件流，避免浏览器卡死
      await sendToWormHole(stream);
      throw err;
    }
    const fileUrl = `${this.static.dir}/temporary/${filename}`;
    const userData =await this.service.import(fileUrl)
    setTimeout(() => {
      this.user.insertUser(userData)
      // 判断是否为文件
          fs.unlink(fileUrl, (err) => {
            if (err) throw err;
            console.log('成功删除' + fileUrl);
          });
    });
    this.ctx.body=200
  }

  @get('/exportUsers')
  async exportUsers(){
    await this.util.mkdirFolder('download')
    const res =  await this.service.download()
    if (res) {
      const filePath = path.resolve(this.static.dir, 'download/用户账号管理.xlsx');
      const fileName = `用户账号管理${moment(new Date).format('YYYY-MM')}.xlsx`;
      this.ctx.attachment(fileName);
      this.ctx.set('content-type', 'application/octet-stream');
      // 自定义请求头，用来判断文件下载
      this.ctx.set('download-type', 'file');
      this.ctx.body = fs.createReadStream(filePath);
    }
  }
}
